﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Xml.Serialization;
using AliyunMobileTestPlatform.Models;
using SharpSvn;
using System.Net;
using System.Web.Configuration;
using SharpSvn.Security;

namespace AliyunMobileTestPlatform.Controllers
{
    public class CoverageController : Controller
    {
        // SVN 每个版本的数据都存储在db\revs\ 下，每1000个文件为一个文件夹，从0开始编号，所以版本67对应的文件为db\revs\0\67
        private string PROJECTS_INFO_FILE_PATH = @"D:\SVNServer\Repositories\projects.xml";
        private string TEMP = @"d:\temp\";
        private string COVERAGESUMMARY_FILENAME = "coverage.sum";
        private string EC_FOLDER = @"testresults\";
        private string APP_FOLDER = @"apps\";
        private string APP_NAME = "Contacts_intermediates";
        private string TAG_FOLDER = @"tags\";
        private string TRUNK_FOLDER = @"trunk\";
        private static string BUILTIN_ADMIN = WebConfigurationManager.AppSettings["BUILTIN_ADMIN"].ToString();
        private static string BUILTIN_PWD = WebConfigurationManager.AppSettings["BUILTIN_PWD"].ToString();
        private static string BUILTIN_DOMAIN = WebConfigurationManager.AppSettings["BUILTIN_DOMAIN"].ToString();

        //

        // GET: /Coverage/
        public ActionResult Index()
        {
            List<ProjectModel> pc;
            using (FileStream fs = System.IO.File.OpenRead(PROJECTS_INFO_FILE_PATH))
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<ProjectModel>));
                    pc = serializer.Deserialize(fs) as List<ProjectModel>;
                }
                catch
                {
                    return View();
                }
            }
            return View(pc);
        }

        public JavaScriptResult GetCoverage(string id, string revision)
        {
            string svnLocalPath = Encoding.Default.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(id)));
            
            int appNameIndex = svnLocalPath.LastIndexOf('\\') + 1;
            APP_NAME = svnLocalPath.Substring(appNameIndex);

            string ecFileFullPath = svnLocalPath + "/../../" + EC_FOLDER + APP_NAME + "/";
            ParserCovXML.AllCovData covData;
            string sumFilePath = svnLocalPath + "/" + COVERAGESUMMARY_FILENAME;
            //如果结果文件存在
            if (System.IO.File.Exists(sumFilePath))
            {
                covData = ParserCovXML.GenerateReportHelper.unSerialize(sumFilePath);
                if (!covData.SVNRevision.Equals(revision))
                {
                    try
                    {
                        ParserCovXML.GenerateReportHelper.GenerateXMLReport(ecFileFullPath, svnLocalPath);
                    }
                    catch (ArgumentException ex) 
                    {
                        if (ex.Message.Equals("Can not find ec file.")) 
                        {
                            return JavaScript("$(\"#chartcontainer\").html(\"\");alert(\"没有覆盖率记录\")");
                        }
                    }
                    covData = ParserCovXML.GenerateReportHelper.ParserCovXML(svnLocalPath + "/coverage.xml", APP_NAME);
                    covData.SVNRevision = revision;
                    ParserCovXML.GenerateReportHelper.Serialize(sumFilePath, covData);
                }
            }
            else
            {
                try
                {
                    ParserCovXML.GenerateReportHelper.GenerateXMLReport(ecFileFullPath, svnLocalPath);
                }
                catch (ArgumentException ex)
                {
                    if (ex.Message.Equals("Can not find ec file."))
                    {
                        return JavaScript("$(\"#chartcontainer\").html(\"\");alert(\"没有覆盖率记录\");");
                    }
                }
                covData = ParserCovXML.GenerateReportHelper.ParserCovXML(svnLocalPath + "/coverage.xml", APP_NAME);
                covData.SVNRevision = revision;
                ParserCovXML.GenerateReportHelper.Serialize(sumFilePath, covData);
            }
            return JavaScript(ParserCovXML.GenerateReportHelper.GenerateJS(covData));
        }

        public ActionResult GetApps(string id)
        {
            string svnUrl = Encoding.Default.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(id)));
            int index = svnUrl.IndexOf("svn");
            bool result = false;
            SvnUpdateResult updateResult;
            string appPath = "";

            //分支主干路径
            if (index > 0)
            {
                string tempPath = svnUrl.Substring(index + 4);

                //有em文件的App目录
                //appPath = TEMP + tempPath + "/" + TRUNK_FOLDER + APP_FOLDER;

                //
                appPath = TEMP + tempPath + "/" + TRUNK_FOLDER + EC_FOLDER;
                //如果本地工作目录不存在，则全部拉取,否则更新目录
                if (!Directory.Exists(TEMP + tempPath))
                {
                    using (SvnClient client = new SvnClient())
                    {
                        client.Authentication.Clear();
                        client.Authentication.DefaultCredentials = new NetworkCredential(BUILTIN_ADMIN, BUILTIN_PWD, BUILTIN_DOMAIN);
                        client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                        {
                            e.AcceptedFailures = e.Failures;
                            e.Save = true;
                        };
                        result = client.CheckOut(new SvnUriTarget(svnUrl), TEMP + tempPath, out updateResult);
                    }
                }
                else
                {
                    using (SvnClient client = new SvnClient())
                    {
                        client.Authentication.Clear();
                        client.Authentication.DefaultCredentials = new NetworkCredential(BUILTIN_ADMIN, BUILTIN_PWD, BUILTIN_DOMAIN);
                        client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                        {
                            e.AcceptedFailures = e.Failures;
                            e.Save = true;
                        };
                        result = client.Update(TEMP + tempPath, out updateResult);
                    }
                }
            }
            //基线路径
            else
            {
                appPath = svnUrl + "/" + EC_FOLDER;
                using (SvnClient client = new SvnClient())
                {
                    client.Authentication.Clear();
                    client.Authentication.DefaultCredentials = new NetworkCredential(BUILTIN_ADMIN, BUILTIN_PWD, BUILTIN_DOMAIN);
                    client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                    {
                        e.AcceptedFailures = e.Failures;
                        e.Save = true;
                    };
                    result = client.Update(svnUrl, out updateResult);
                }
            }

            //获取APP列表,如果目录不存在,返回empty
            if (!Directory.Exists(appPath))
            {
                return Content("empty");
            }
            string[] appNames = Directory.GetDirectories(appPath);
            if (appNames.Length < 1)
            {
                return Content("empty");
            }
            else
            {
                for (int i = 0; i < appNames.Length;i++ )
                {
                    // 以\开头\结尾，保证不会替换Name中可能包含的TESTRESULTS字符串
                    appNames[i] = appNames[i].Replace('/', '\\').Replace("\\" + EC_FOLDER, "\\" + APP_FOLDER);
                }
                AppsModel apps = new AppsModel(appNames, updateResult.Revision.ToString());
                string s = apps.ToHtml();
                return Content(apps.ToHtml());
            }
        }

        public ActionResult GetTags(string id, string pName, string bName)
        {
            string svnUrl = Encoding.Default.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(id)));
            string tempPath = svnUrl.Substring(svnUrl.IndexOf("svn") + 4);
            bool result = false;
            SvnUpdateResult updateResult;
            //如果本地工作目录不存在，则全部拉取,否则更新目录
            if (!Directory.Exists(TEMP + tempPath))
            {
                using (SvnClient client = new SvnClient())
                {
                    client.Authentication.Clear();
                    client.Authentication.DefaultCredentials = new NetworkCredential(BUILTIN_ADMIN, BUILTIN_PWD, BUILTIN_DOMAIN);
                    client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                    {
                        e.AcceptedFailures = e.Failures;
                        e.Save = true;
                    };
                    result = client.CheckOut(new SvnUriTarget(svnUrl), TEMP + tempPath, out updateResult);
                }
            }
            else
            {
                using (SvnClient client = new SvnClient())
                {
                    client.Authentication.Clear();
                    client.Authentication.DefaultCredentials = new NetworkCredential(BUILTIN_ADMIN, BUILTIN_PWD, BUILTIN_DOMAIN);
                    client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                    {
                        e.AcceptedFailures = e.Failures;
                        e.Save = true;
                    };
                    result = client.Update(TEMP + tempPath, out updateResult);
                }
            }
            //获取APP列表
            string[] tagNames = Directory.GetDirectories(TEMP + tempPath + "/" + TAG_FOLDER);
            TagsModel tags = new TagsModel(tagNames, pName, bName);
            return Content(tags.ToHtml());
        }

        public JavaScriptResult GetHistory(string id) 
        {
            string svnLocalPath = Encoding.Default.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(id)));
            string historyPath = svnLocalPath.Replace("/", "\\").Replace("\\trunk\\apps", "\\history\\");
            if (!Directory.Exists(historyPath))
                return JavaScript("alert(\"没有历史记录！\")");
            string s = ParserCovXML.GenerateReportHelper.GenerateHistoryJS(historyPath);
            return JavaScript(ParserCovXML.GenerateReportHelper.GenerateHistoryJS(historyPath));
        }
    }
}
